package com.tina.controller;

import com.tina.common.PropertiesUtils;
import com.tina.common.ResultUtils;
import com.tina.entity.Chunk;
import com.tina.services.imppl.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * * 文件Controller
 * * 处理文件的上传与下载
 *
 * @author tina
 * @since 2021-10-15 11:00
 */
@RestController
public class FileController {

    @Autowired
   private FileService fileService;

    /**
     * 返回文件列表
     *
     * @param response 响应
     * @return 文件列表map
     */
    @RequestMapping("/fileList")
    public Map<String, Object> filelist(HttpServletResponse response) throws IOException {
        return ResultUtils.result(fileService.getFileList());
    }

    /**
     * 文件下载
     *
     * @param name     文件名（页面传递过来的参数)
     * @param request  请求
     * @param response 响应
     */
    @RequestMapping("/download")
    public void down(@RequestParam("fileMd5") String fileMd5, @RequestParam("name") String name, HttpServletRequest request, HttpServletResponse response) {
        fileService.fileDownload(fileMd5, name, request, response);
    }


    /**
     * 处理文件上传POST请求
     * 将上传的文件存放到服务器内
     *
     * @param chunk    文件块
     * @param response 响应
     * @return 上传响应状态
     */
    @PostMapping("/fileUpload")
    public Map<String, Object> uploadPost(@ModelAttribute Chunk chunk, HttpServletResponse response) {
        return ResultUtils.result(fileService.fileUploadPost1(chunk, response));
    }

    /**
     * 处理文件上传GET请求
     * 验证上传的文件块，是否允许浏览器再次发送POST请求（携带二进制文件的请求流，FormData）
     *
     * @param identifier 文件MD5值
     * @return 文件块
     */
    @GetMapping("/fileUpload")
    public Map<String, Object> uploadGet(@ModelAttribute Chunk chunk, HttpServletResponse response) {
        boolean flag = fileService.fileUploadGet(chunk);
        Integer code = 200;
        if (!flag) {
            code = 304;
        }
        response.setStatus(code);
        return ResultUtils.result(code, chunk);
    }

}
